﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NetDon.OA.Portal.HtmlTool;
using NetDon.Utilities;
using NetDon.Variation.Data.CollectionClasses;
using NetDon.Variation.Data.EntityClasses;
using NetDon.Variation.Data.HelperClasses;
using NetDon.WebControls;


namespace NetDon.OA.Portal.Product
{
    public partial class VariationProductEdit : NetDonPage
    {
        #region Properties
        protected int Id
        {
            get
            {
                return Parameters.GetInt32("Id");
            }
        }

        private IList<VariationProudctSKUData> VariationProudcts
        {
            set { ViewState["VariationProudcts"] = value; }
            get
            {
                if (ViewState["VariationProudcts"] != null)
                    return ViewState["VariationProudcts"] as IList<VariationProudctSKUData>;
                return new List<VariationProudctSKUData>();
            }
        }


        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {


            if (!IsPostBack)
            {

                CancelButton = btnReturn;

                if (Id > 0)
                {

                    var account = new VariationproductEntity();
                    account.FetchUsingPK(Id);
                    panelCustomInfo.DataSource = account;
                    panelCustomInfo.DataBind();
                    //bind tempalte
                    var service = new VariationProductService();


                    this.gridCustomerInfoList.DataSource = VariationProudcts = service.SearchVariationProductSKUs(Id).ToList();
                    this.gridCustomerInfoList.DataBind();


                }
                AddEmptyIssuingOrderDeliveryAndBind();

            }
        }






        protected void gridCustomerInfoList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var id = (e.Row.DataItem as VariationProudctSKUData).Id.ToString();



                var btnDelete = (ImageButton)e.Row.FindControl("btnDelete");

                btnDelete.OnClientClick = string.Format("deleteIssuingOrderDeliveryId('{0}');return false;",
                                                        id);


                var txtSubSKU = (TextBox)e.Row.FindControl("txtSubSKU");
                var txtOrderQuantity = (TextBox)e.Row.FindControl("txtOrderQuantity");

                txtSubSKU.Attributes.Add("onblur",
                                         "onChangeDeliveryCode(this,'" + txtOrderQuantity.ClientID +
                                         "'," + e.Row.RowIndex + ");return false;");
            }

        }

        private bool save()
        {
            ExtractIssuingOrderDelivery();
            foreach (var issuingOrderDeliery in this.VariationProudcts)
            {

                if (string.IsNullOrWhiteSpace(issuingOrderDeliery.Subsku))
                {
                    continue;
                }
                if (VariationProudcts.Count(product=>product.Subsku == issuingOrderDeliery.Subsku)>1)
                {
                    Alert("子SKU{0}重复，请重新输入！".Formato(issuingOrderDeliery.Subsku));
                    return false;
                }
                if (!issuingOrderDeliery.Quantity.HasValue)
                {
                    Alert("请输入数量（子SKU{0})！".Formato(issuingOrderDeliery.Subsku));
                    return false;
                }
            }

            VariationproductEntity entity = null;
            if (Id > 0)
            {
                entity = new VariationproductEntity(Id);

            }
            else
            {
                entity = new VariationproductEntity();
            }
           //check duplicated name
            var collection = new VariationproductCollection();
            if (Id > 0)
            {
                collection.GetMulti(VariationproductFields.Sku == txtSKU.Text.Trim() & VariationproductFields.Id != Id);
            }
            else
            {
                collection.GetMulti(VariationproductFields.Sku == txtSKU.Text.Trim());
               
            }
            if(collection.Count>0)
            {
                Alert("组合SKU不可以重复，请重新输入！");
                return false;
            }
            var trans = new Transaction(IsolationLevel.ReadCommitted, "saveHtmlVariationProduct");
            try
            {
             
                entity.Sku = txtSKU.Text.Trim();
                entity.Name = txtName.Text.Trim();
                trans.Add(entity);
                entity.Save();
          

                foreach (var issuingOrderDelivery in VariationProudcts)
                {
                    var issuingOrderDeliveryEntity = new VariationproductskusEntity();
                    var issuingOrderDeliveryIdValue = issuingOrderDelivery.Id.ToInt32();
                    if (!issuingOrderDeliveryIdValue.HasValue)
                    {
                        if (string.IsNullOrWhiteSpace(issuingOrderDelivery.Subsku))
                        {
                            continue;
                        }
                 

                    }
                    else
                    {
                        issuingOrderDeliveryEntity = new VariationproductskusEntity(issuingOrderDeliveryIdValue.Value);
                        if (string.IsNullOrWhiteSpace(issuingOrderDelivery.Subsku))
                        {
                            issuingOrderDeliveryEntity.Delete();
                            trans.Add(issuingOrderDeliveryEntity);
                            issuingOrderDeliveryEntity.Save();
                            continue;
                        }
                    }
                    issuingOrderDeliveryEntity.Subsku = issuingOrderDelivery.Subsku;
                    issuingOrderDeliveryEntity.Variationproduct = entity;
                    issuingOrderDeliveryEntity.Quantity = issuingOrderDelivery.Quantity;

                    trans.Add(issuingOrderDeliveryEntity);
                    issuingOrderDeliveryEntity.Save();

                }
               

                trans.Commit();



            }
            catch (Exception)
            {
                trans.Rollback();
                throw;
            }


            return true;
        }
        protected void btnIssuingOrderDeliveryDelete_Click(object sender, EventArgs e)
        {
            var issuingOrderDeliveryId = hfdIssuingOrderDeliveryId.Value;
            var issuingOrderDelivery =
                VariationProudcts.FirstOrDefault(src => src.Id == issuingOrderDeliveryId);
            if (issuingOrderDelivery != null)
            {
                VariationProudcts.Remove(issuingOrderDelivery);
                var issuingOrderDeliveryIdValue = issuingOrderDeliveryId.ToInt32();
                if (issuingOrderDeliveryIdValue.HasValue)
                {
                    //delete from database
                    new VariationProductService().RemoveVariationProductSKU(issuingOrderDeliveryIdValue.Value);
                }
               
            }
            ExtractIssuingOrderDelivery();
            gridCustomerInfoList.DataSource = VariationProudcts;
            gridCustomerInfoList.DataBind();
        }


        private void ExtractIssuingOrderDelivery()
        {
            var tempIssuingOrderDeliveries = new List<VariationProudctSKUData>();
            foreach (GridViewRow detailRow in gridCustomerInfoList.Rows)
            {
                var issuingOrderDeliveryId = gridCustomerInfoList.DataKeys[detailRow.RowIndex]["Id"].ToString();
                var issuingOrderDelivery = VariationProudcts.FirstOrDefault(src => src.Id == issuingOrderDeliveryId);

                if (issuingOrderDelivery != null)
                {
                    issuingOrderDelivery.Variationproductid = Id;

                    issuingOrderDelivery.Subsku = (detailRow.FindControl("txtSubSKU") as TextBox).Text.Trim();
                    issuingOrderDelivery.Quantity = (detailRow.FindControl("txtOrderQuantity") as TextBox).Text.Trim().ToInt32();

                    tempIssuingOrderDeliveries.Add(issuingOrderDelivery);
                }

            }

            //update viewstate
            VariationProudcts = tempIssuingOrderDeliveries;
        }

        public void txtDeliveryOrderCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(HiddenDeliveryCode.Value))
            {
                ExtractIssuingOrderDelivery();
            }

            AddEmptyIssuingOrderDeliveryAndBind();
            GenerateOrderDeliveryCode();
        }
        private void AddEmptyIssuingOrderDeliveryAndBind()
        {
            var tempIssuingOrderDeliveries = VariationProudcts;
            tempIssuingOrderDeliveries.Add(new VariationProudctSKUData()
            {
                Id =Guid.NewGuid().ToString(),
                Variationproductid = Id

            });
            VariationProudcts = tempIssuingOrderDeliveries; //update viewstate
            gridCustomerInfoList.DataSource = VariationProudcts;
            gridCustomerInfoList.DataBind();
        }

        void GenerateOrderDeliveryCode()
        {

            bool isChanged = false;
            int i = 0;
            foreach (var issuingOrderDeliveryData in VariationProudcts)
            {
                if (!string.IsNullOrEmpty(issuingOrderDeliveryData.Subsku))
                {

                    if (!string.IsNullOrWhiteSpace(HiddenRowIndex.Value))
                    {
                        if (HiddenRowIndex.Value == i.ToString())
                        {
                            isChanged = true;
                            var productInfo = ProductXiaoSoftService.GetProductInfo(issuingOrderDeliveryData.Subsku);
                            issuingOrderDeliveryData.GoodsName = productInfo.ProductName;
                            issuingOrderDeliveryData.Spec = productInfo.Spec;
                            issuingOrderDeliveryData.StockQuantity = productInfo.StockQuantity;
                            break;
                        }
                    }
                    else
                    {
                        
                    }


                }
                i++;
            }
            if (isChanged)
            {
                VariationProudcts = VariationProudcts;
                gridCustomerInfoList.DataSource = VariationProudcts;
                gridCustomerInfoList.DataBind();
            }



        }

        protected void btnSave_Click(object sender, EventArgs e)
        {

            if (save())
            {
                Success("保存成功!");
                CloseWindow(true);
            }



        }



    }



}